package com.example.yilanchatserver.business.freechat.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.yilanchatserver.business.freechat.*;
import com.example.yilanchatserver.business.freechat.service.RedisService;
import com.example.yilanchatserver.business.freechat.service.ZhiPuService;
import com.example.yilanchatserver.business.freechat.service.dto.*;

import com.example.yilanchatserver.dal.knowledge.entity.ContentlistEntity;
import com.example.yilanchatserver.dal.knowledge.entity.KnowledgeEntity;
import com.example.yilanchatserver.dal.knowledge.entity.SpaceEntity;
import com.example.yilanchatserver.dal.knowledge.mapper.ContentlistMapper;
import com.example.yilanchatserver.dal.knowledge.mapper.KnowledgeMapper;
import com.example.yilanchatserver.dal.knowledge.mapper.SpaceMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.example.yilanchatserver.business.freechat.HttpUtilClient.transferToFile;

@Service
@RequiredArgsConstructor
@Slf4j
public class ZhiPuServiceImpl implements ZhiPuService {

    @Resource
    private final ZhiPuWebClient zhiPuWebClient;

    @Resource
    private final ZhiPuPromptWebClient zhiPuPromptWebClient;

    @Resource
    private RedisService redisService;

    @Resource
    private SpaceMapper spaceMapper;

    @Resource
    private KnowledgeMapper knowledgeMapper;

    @Resource
    private ContentlistMapper contentlistMapper;

    private String tokenKey = "wudao:token:";

    private static String API_KEY = "b54183298cd44d3e9391c3426e70a7fe";

    private static String PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIMuLoUbpKWDdrj8/sniPR2u37D5gJFfBzBQCLNAKJb9MwelEGmGeUotU2XMEdqk7Uq4tBzOmaOudFeXgc02J90CAwEAAQ==";

    private static String AUTH_TOKEN_URL = "https://maas.aminer.cn/api/paas/passApiToken/createApiToken";

    @Value("${wudao.url.knowledge.baseline}")
    private String baselineURL;

    @Value("${wudao.url.knowledge.embedding}")
    private String embeddingURL;


    @Value("${wudao.url.knowledge.knowledge}")
    private String knowledgeURL;

    @Value("${wudao.url.knowledge.document}")
    private String documentURL;

    @Value("${wudao.url.knowledge.uploadDocument}")
    private String uploadDocumentURL;

    @Value("${wudao.url.knowledge.uploadUrl}")
    private String uploadUrlURL;

    @Value("${wudao.url.knowledge.application}")
    private String applicationURL;

    @Value("${wudao.key.baseBase}")
    private String baseBase;






    @Override
    public Flux<String> send(FreeChatDTO chatDTO, String authToken, String talkerUUid) {
        final String talkUUid = talkerUUid;



//        Message userMessage = new Message(MessageType.TEXT, UserType.USER, content);
//        int currentToken = (int) (content.length() / TOKEN_CONVERSION_RATE);
//        List<Message> history = userSessionUtil.getHistory(sessionId, MessageType.TEXT, (int) ((MAX_TOKEN / TOKEN_CONVERSION_RATE) - currentToken));
//        log.info("history:{}", history);
//        String historyDialogue = history.stream().map(e -> String.format(e.getUserType().getCode(), e.getMessage())).collect(Collectors.joining());

//        String prompt = StringUtils.hasLength(historyDialogue) ? String.format("%sQ:%s\nA: ", historyDialogue, content) : content;

        return Flux.create(emitter -> {
            ZhiPuSubscriber subscriber = new ZhiPuSubscriber(emitter);
            Flux<String> zhiPuResponse =
                    zhiPuWebClient.getChatResponse(chatDTO, authToken, null, 0.95, 0.7, talkUUid);
            zhiPuResponse.subscribe(subscriber);
            emitter.onDispose(subscriber);
        });
    }

    @Override
    public Flux<String> sendWithPrompt(FreeChatPromptDTO chatDTO, String authToken) {


//        Message userMessage = new Message(MessageType.TEXT, UserType.USER, content);
//        int currentToken = (int) (content.length() / TOKEN_CONVERSION_RATE);
//        List<Message> history = userSessionUtil.getHistory(sessionId, MessageType.TEXT, (int) ((MAX_TOKEN / TOKEN_CONVERSION_RATE) - currentToken));
//        log.info("history:{}", history);
//        String historyDialogue = history.stream().map(e -> String.format(e.getUserType().getCode(), e.getMessage())).collect(Collectors.joining());

//        String prompt = StringUtils.hasLength(historyDialogue) ? String.format("%sQ:%s\nA: ", historyDialogue, content) : content;



        return Flux.create(emitter -> {
            ZhiPuPromptSubscriber subscriber = new ZhiPuPromptSubscriber(emitter);
            Flux<String> zhiPuResponse =
                    zhiPuPromptWebClient.getChatResponse(chatDTO, authToken, null, chatDTO.getTemperature(), chatDTO.getTopP());
            zhiPuResponse.subscribe(subscriber);
            emitter.onDispose(subscriber);
        });
    }

    @Override
    public Flux<String> sendTest(FreeChatPromptDTO freeChatPromptDTO, String authToken, String knowledgeId) throws Exception {
        ZhiPuApplicationData zhiPuApplicationData = new ZhiPuApplicationData();
        List<String> list = new ArrayList<>();
        list.add(knowledgeId);
        zhiPuApplicationData.setKnowledge_ids(list);
        zhiPuApplicationData.setPrompt(freeChatPromptDTO.getPrompt().get(0).get("text"));
        zhiPuApplicationData.setDesc("白板机器人，不设prompt");
        zhiPuApplicationData.setName("白板机器人");
        zhiPuApplicationData.setId(freeChatPromptDTO.getRobotId());
        zhiPuApplicationData.setTemperature(String.valueOf(freeChatPromptDTO.getTemperature()));
        zhiPuApplicationData.setTop_p(String.valueOf(freeChatPromptDTO.getTopP()));
        editApplication(zhiPuApplicationData);

        FreeChatDTO chatDTO = JSON.parseObject(JSON.toJSONString(freeChatPromptDTO), FreeChatDTO.class);
        return Flux.create(emitter -> {
            ZhiPuSubscriber subscriber = new ZhiPuSubscriber(emitter);
            Flux<String> zhiPuResponse =
                    zhiPuWebClient.getChatResponse(chatDTO, authToken, null, 1.0, 1.0, null);
            zhiPuResponse.subscribe(subscriber);
            emitter.onDispose(subscriber);
        });
    }

    @Override
    public void resetTalkList(String userAccount) {
        redisService.remove(userAccount);
    }

    public String getToken() throws Exception {
        try {
            String token = redisService.get(tokenKey);
            if(StringUtils.isEmpty(token)){
                Map<String, Object> resultMap = WuDaoUtils.getToken(AUTH_TOKEN_URL, API_KEY, PUBLIC_KEY);
                int code = (int) resultMap.get("code");
                if (code == 200) {
                    token = String.valueOf(resultMap.get("data"));
                    redisService.set(tokenKey, token, 8, TimeUnit.HOURS);
                }
                else {
                    throw new BusinessException(BusinessErrorCodes.DEFAULT_BUSINESS_ERROR);
                }
            }
            return token;
        } catch (Exception e) {
            log.error("获取token失败", e);
            throw e;
        }
//        return null;
    }

    public String connectHTTP(String URL, String params, String type) throws Exception {
        String token = getToken();
        Map header = new HashMap<>();
        header.put("Content-type", "application/json; charset=utf-8");
        header.put("Authorization", "Bearer "+token);
        if(Objects.equals(type, "GET")){
            return HttpUtilClient.sendGetJson(URL, params, header);
        } else if (Objects.equals(type, "POST")) {
            return HttpUtilClient.sendPostJson(URL, params, header);
        } else if (Objects.equals(type, "PUT")) {
            return HttpUtilClient.sendPutJson(URL, params, header);
        } else if (Objects.equals(type, "DELETE")) {
            return HttpUtilClient.sendDeleteJson(URL, params, header);
        } else {
            throw new Exception("不存在的连接类型");
        }
    }

    public String connectHTTP(String URL, Map<String, String> params, String type) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("Content-type", "application/json; charset=utf-8");
        header.put("Authorization", "Bearer "+token);
        if(Objects.equals(type, "GET")){
            return HttpUtilClient.sendGet(URL, params, header);
        } else if (Objects.equals(type, "POST")) {
            return HttpUtilClient.sendPostJson(URL, JSON.toJSONString(params), header);
        } else if (Objects.equals(type, "PUT")) {
            return HttpUtilClient.sendPutJson(URL, JSON.toJSONString(params), header);
        } else if (Objects.equals(type, "DELETE")) {
            return HttpUtilClient.sendDelete(URL, params, header);
        } else {
            throw new Exception("不存在的连接类型");
        }

    }

    public String fileHTTP(String URL, Map params) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", "Bearer "+token);
        return HttpUtilClient.sendPostFile(URL, params, header);

    }

    public <T> Map commonConnection(String URL, T inputDTO, String type) throws Exception {
        log.info("调用接口："+URL);
        Map paramsMap = JSON.parseObject(JSON.toJSONString(inputDTO), Map.class);
        String response = connectHTTP(URL, JSON.toJSONString(paramsMap), type);
        Map resultMap = JSON.parseObject(response, Map.class);
        Integer isSuccess = (Integer) resultMap.get("code");
        if(isSuccess != 200 && isSuccess != 0){
            throw new Exception("发送失败：" + (String)resultMap.get("message"));
        }
        else{
            Map data = resultMap.get("data") == null ? new HashMap<>() : (Map) resultMap.get("data");
            return data;
        }
    }

    public Map commonConnection(String URL, Map<String, String> inputDTO, String type) throws Exception {
        log.info("调用接口："+URL);
        String response = connectHTTP(URL, inputDTO, type);
        Map resultMap = JSON.parseObject(response, Map.class);
        Integer isSuccess = (Integer) resultMap.get("code");
        if(isSuccess != 200 && isSuccess != 0){
            throw new Exception("发送失败：" + (String)resultMap.get("message"));
        }
        else{
            Map data = resultMap.get("data") == null ? new HashMap<>() : (Map) resultMap.get("data");
            return data;
        }
    }

    public Map fileConnection(String URL, Map inputDTO) throws Exception {

        String response = fileHTTP(URL, inputDTO);
        Map resultMap = JSON.parseObject(response, Map.class);
        Integer isSuccess = (Integer) resultMap.get("code");
        if(isSuccess != 200){
            throw new Exception("发送失败：" + (String)resultMap.get("message"));
        }
        else{
            Map data = (Map) resultMap.get("data");
            return data;
        }
    }

    public Integer checkKnowledgeBase(String knowledgeBaseId) {

        try{
            // 如果智谱官网不存在这一知识库，直接删去
            YiLanKnowledgeData yiLanKnowledgeData = getKnowledgeBase(knowledgeBaseId);
            if(Objects.equals(yiLanKnowledgeData.getName(), "METAH默认知识库") && Objects.equals(yiLanKnowledgeData.getDescription(), "METAHCloud所有角色共用的知识库，请勿添加知识或删除")){
                return 2;
            }
            return 1;
            } catch (Exception e) {
                QueryWrapper deleteQueryWrapper = new QueryWrapper<>();
                deleteQueryWrapper.eq("knowledge_id", knowledgeBaseId);
                knowledgeMapper.delete(deleteQueryWrapper);
                return -1;
            }
    }

    public String findBase(YiLanGetKnowledgeBaseListDTO yiLanGetKnowledgeBaseListDTO, String spaceId) throws Exception {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("size", "2000");
        Map data = commonConnection(baselineURL+knowledgeURL, hashMap, "GET");
        List dataList = (List) data.get("list");
        for(Object k : dataList){
            YiLanKnowledgeData yiLanKnowledgeData = JSON.parseObject(JSON.toJSONString(k), YiLanKnowledgeData.class);
            if(Objects.equals(yiLanKnowledgeData.getName(), "METAH默认知识库") && Objects.equals(yiLanKnowledgeData.getDescription(), "METAHCloud所有角色共用的知识库，请勿添加知识或删除")){
                log.warn("智谱中默认知识库存在");
                KnowledgeEntity knowledgeEntity = JSON.parseObject(JSON.toJSONString(yiLanGetKnowledgeBaseListDTO), KnowledgeEntity.class);
                knowledgeEntity.setSpaceId(spaceId);
                knowledgeEntity.setKnowledgeId(Long.parseLong(yiLanKnowledgeData.getId()));
                knowledgeMapper.insert(knowledgeEntity);
                return yiLanKnowledgeData.getId();
            }
        }
        // 说明智谱那边也没有默认知识库了，新建一个
        log.warn("智谱中默认知识库也不存在");
        YiLanCreateKnowledgeBaseDTO yiLanCreateKnowledgeBaseDTO = JSON.parseObject(JSON.toJSONString(yiLanGetKnowledgeBaseListDTO), YiLanCreateKnowledgeBaseDTO.class);
        yiLanCreateKnowledgeBaseDTO.setName("METAH默认知识库");
        yiLanCreateKnowledgeBaseDTO.setDescription("METAHCloud所有角色共用的知识库，请勿添加知识或删除");
        yiLanCreateKnowledgeBaseDTO.setSpaceId(spaceId);
        String id = createKnowledgeBase(yiLanCreateKnowledgeBaseDTO);
        return id;
    }

    public String getLocalApplication(YiLanGetKnowledgeBaseListDTO yiLanGetKnowledgeBaseListDTO) {
        QueryWrapper<SpaceEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product", yiLanGetKnowledgeBaseListDTO.getProduct());
        queryWrapper.eq("user_id", yiLanGetKnowledgeBaseListDTO.getUserId());
        queryWrapper.eq("virtual_role_uk",yiLanGetKnowledgeBaseListDTO.getVirtualRoleUk());
        queryWrapper.eq("service", "zhipu");
        SpaceEntity spaceEntity = spaceMapper.selectOne(queryWrapper);
        return spaceEntity.getSpaceId();
    }


    @Override
    public YiLanCreateSpaceVO createSpace(YiLanCreateSpaceDTO zhiPuCreateSpaceDTO) throws Exception {
        System.out.println(zhiPuCreateSpaceDTO);
        QueryWrapper<SpaceEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product", zhiPuCreateSpaceDTO.getProduct());
        queryWrapper.eq("user_id", zhiPuCreateSpaceDTO.getUserId());
        queryWrapper.eq("virtual_role_uk",zhiPuCreateSpaceDTO.getVirtualRoleUk());
        queryWrapper.eq("service", "zhipu");
        SpaceEntity spaceEntity = spaceMapper.selectOne(queryWrapper);
        YiLanCreateSpaceVO yiLanCreateSpaceVO = new YiLanCreateSpaceVO();
        String spaceId = null;
        if (null == spaceEntity) {
            ZhiPuApplicationData zhiPuApplicationData = JSON.parseObject(JSON.toJSONString(zhiPuCreateSpaceDTO), ZhiPuApplicationData.class);
            zhiPuApplicationData.setName(zhiPuCreateSpaceDTO.getUserId() + "的" + zhiPuCreateSpaceDTO.getVirtualRoleUk());
//            YiLanCreateKnowledgeBaseDTO yiLanCreateKnowledgeBaseDTO = JSON.parseObject(JSON.toJSONString(zhiPuCreateSpaceDTO), YiLanCreateKnowledgeBaseDTO.class);
//            yiLanCreateKnowledgeBaseDTO.setDescription(zhiPuCreateSpaceDTO.getUserId() + "的" + zhiPuCreateSpaceDTO.getVirtualRoleUk() + "的默认知识库");
            KnowledgeEntity insertKnowledgeEntity = JSON.parseObject(JSON.toJSONString(zhiPuCreateSpaceDTO), KnowledgeEntity.class);
            insertKnowledgeEntity.setKnowledgeId(Long.parseLong(baseBase));
            String tmpSpaceId = UUID.randomUUID().toString();
            insertKnowledgeEntity.setSpaceId(tmpSpaceId);
            System.out.println(insertKnowledgeEntity);
            knowledgeMapper.insert(insertKnowledgeEntity);
            String knowledgeId = baseBase;
            List<String> knowledgeIds = new ArrayList<>();
            knowledgeIds.add(knowledgeId);
            zhiPuApplicationData.setKnowledge_ids(knowledgeIds);
            spaceId = createApplication(zhiPuApplicationData);
            spaceEntity = new SpaceEntity();
            spaceEntity.setSpaceId(spaceId);
            spaceEntity.setService("zhipu");
            spaceEntity.setVirtualRoleUk(zhiPuCreateSpaceDTO.getVirtualRoleUk());
            spaceEntity.setProduct(zhiPuCreateSpaceDTO.getProduct());
            spaceEntity.setUserId(zhiPuCreateSpaceDTO.getUserId());
            spaceMapper.insert(spaceEntity);
            QueryWrapper<KnowledgeEntity> queryWrapper1 = new QueryWrapper<>();
            System.out.println(knowledgeId);
            queryWrapper1.eq("knowledge_id", knowledgeId);
            queryWrapper1.eq("space_id", tmpSpaceId);
//            System.out.println(knowledgeMapper.selectList(queryWrapper1));
            KnowledgeEntity knowledgeEntity = knowledgeMapper.selectOne(queryWrapper1);
            knowledgeEntity.setSpaceId(spaceId);
            knowledgeMapper.updateById(knowledgeEntity);

        } else {
            spaceId = spaceEntity.getSpaceId();
        }
        yiLanCreateSpaceVO.setName(zhiPuCreateSpaceDTO.getUserId() + "的" + zhiPuCreateSpaceDTO.getVirtualRoleUk());
        yiLanCreateSpaceVO.setSpaceId(spaceId);
        return yiLanCreateSpaceVO;
    }

    @Override
    public ZhiPuEmbeddingDTO embedding() throws Exception {
        Map data = commonConnection(baselineURL+embeddingURL, new HashMap<>(), "GET");
        return JSON.parseObject(JSON.toJSONString(data), ZhiPuEmbeddingDTO.class);
    }

    @Override
    public String createKnowledgeBase(YiLanCreateKnowledgeBaseDTO yiLanCreateKnowledgeBaseDTO) throws Exception {
        yiLanCreateKnowledgeBaseDTO.setDescription(yiLanCreateKnowledgeBaseDTO.getProduct()+"的"+yiLanCreateKnowledgeBaseDTO.getUserId()+"的知识库");
        Map data = commonConnection(baselineURL+knowledgeURL, yiLanCreateKnowledgeBaseDTO, "POST");
        if (data.get("id") == null) {
            throw new Exception((String) data.get("message"));
        }
        System.out.println(data);
        Long id =  Long.parseLong((String) data.get("id"));
        KnowledgeEntity knowledgeEntity = JSON.parseObject(JSON.toJSONString(yiLanCreateKnowledgeBaseDTO), KnowledgeEntity.class);
        knowledgeEntity.setKnowledgeId(id);
        System.out.println(knowledgeEntity);
        knowledgeMapper.insert(knowledgeEntity);
        return (String) data.get("id");
    }

    @Override
    public void updateKnowledgeBase(YiLanCreateKnowledgeBaseDTO zhiPuUpdateKnowledgeBaseDTO) throws Exception {
        zhiPuUpdateKnowledgeBaseDTO.setDescription(zhiPuUpdateKnowledgeBaseDTO.getProduct()+"的"+zhiPuUpdateKnowledgeBaseDTO.getUserId()+"的知识库");
        Integer isChecked = checkKnowledgeBase(zhiPuUpdateKnowledgeBaseDTO.getId());
        if(isChecked == -1){
            throw new Exception("数据库不存在，请重试");
        }
        commonConnection(baselineURL+knowledgeURL+"/"+zhiPuUpdateKnowledgeBaseDTO.getId(), zhiPuUpdateKnowledgeBaseDTO, "PUT");
        QueryWrapper<KnowledgeEntity> queryWrapper = new QueryWrapper<>();
        String knowledgeId = zhiPuUpdateKnowledgeBaseDTO.getId();
        queryWrapper.eq("knowledge_id", knowledgeId);
        queryWrapper.eq("service", "zhipu");
        Integer id = knowledgeMapper.selectOne(queryWrapper).getId();

        zhiPuUpdateKnowledgeBaseDTO.setId(null);
        KnowledgeEntity knowledgeEntity = JSON.parseObject(JSON.toJSONString(zhiPuUpdateKnowledgeBaseDTO), KnowledgeEntity.class);
        knowledgeEntity.setKnowledgeId(Long.parseLong(knowledgeId));
        knowledgeEntity.setId(id);
        knowledgeMapper.updateById(knowledgeEntity);
    }

    @Override
    public YiLanGetKnowledgeBaseListVO getKnowledgeBaseList(YiLanGetKnowledgeBaseListDTO zhiPuGetKnowledgeBaseListDTO) throws Exception {
        Integer isBase = 0;
        log.info("获取知识库列表："+JSON.toJSONString(zhiPuGetKnowledgeBaseListDTO));
        QueryWrapper<KnowledgeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", zhiPuGetKnowledgeBaseListDTO.getUserId());
        queryWrapper.eq("product", zhiPuGetKnowledgeBaseListDTO.getProduct());
        queryWrapper.eq("virtual_role_uk", zhiPuGetKnowledgeBaseListDTO.getVirtualRoleUk());
        queryWrapper.eq("service", "zhipu");
        List<KnowledgeEntity> knowledgeEntities = knowledgeMapper.selectList(queryWrapper);
        List<YiLanKnowledgeData> zhiPuKnowledgeListVOS = new ArrayList<>();
        String spaceId = getLocalApplication(zhiPuGetKnowledgeBaseListDTO);

        for(KnowledgeEntity k: knowledgeEntities){
            Map m = JSON.parseObject(JSON.toJSONString(k), Map.class);
            String knowledgeId = Long.toString((Long) m.remove("knowledgeId"));
            Integer isChecked = checkKnowledgeBase(knowledgeId);
            if(isChecked == -1) {
                log.warn(knowledgeId+"在智谱官网不存在，已自动删除");
                continue;
            } else if (isChecked == 2) {
                isBase = 1;
            }
            m.put("id", knowledgeId);
            YiLanKnowledgeData u = JSON.parseObject(JSON.toJSONString(m), YiLanKnowledgeData.class);
            zhiPuKnowledgeListVOS.add(u);
        }

        if(isBase == 0) {
            // 寻找共用默认知识库id
            log.warn("默认知识库不存在了，自建中");
            String id = findBase(zhiPuGetKnowledgeBaseListDTO, spaceId);
            ZhiPuApplicationData zhiPuApplicationData = getApplication(spaceId);
            List<String> knowledgeIds = zhiPuApplicationData.getKnowledge_ids();
            knowledgeIds.add(id);
            editApplication(zhiPuApplicationData);
            YiLanKnowledgeData baseData = getKnowledgeBase(id);
            zhiPuKnowledgeListVOS.add(baseData);
        }
        ZhiPuApplicationData zhiPuApplicationData = getApplication(spaceId);
        List<String> knowledgeIds = zhiPuApplicationData.getKnowledge_ids();
        YiLanGetKnowledgeBaseListVO yiLanGetKnowledgeBaseListVO = new YiLanGetKnowledgeBaseListVO();
        yiLanGetKnowledgeBaseListVO.setList(zhiPuKnowledgeListVOS);
        yiLanGetKnowledgeBaseListVO.setTotal(zhiPuKnowledgeListVOS.size());
        return yiLanGetKnowledgeBaseListVO;
    }

    @Override
    public YiLanKnowledgeData getKnowledgeBase(String id) throws Exception {
        log.info("获取知识库：" + id);
        Map data = commonConnection(baselineURL+knowledgeURL+"/"+id, new HashMap<>(), "GET");
        return JSON.parseObject(JSON.toJSONString(data), YiLanKnowledgeData.class);
    }

    @Override
    public void deleteKnowledgeBase(String id) throws Exception {
        YiLanKnowledgeData yiLanKnowledgeData = getKnowledgeBase(id);
        if(Objects.equals(yiLanKnowledgeData.getName(), "METAH默认知识库") && Objects.equals(yiLanKnowledgeData.getDescription(), "METAHCloud所有角色共用的知识库，请勿添加知识或删除")){
            throw new Exception("无法删除默认知识库");
        }
        commonConnection(baselineURL+knowledgeURL+"/"+id, new HashMap<>(), "DELETE");
        QueryWrapper<KnowledgeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("knowledge_id", id);
        queryWrapper.eq("service", "zhipu");
        KnowledgeEntity knowledgeEntity = knowledgeMapper.selectOne(queryWrapper);
        knowledgeMapper.deleteById(knowledgeEntity);
    }

    @Override
    public ZhiPuKnowledgeBaseCapacityVO knowledgeBaseCapacity() throws Exception {
        Map data = commonConnection(baselineURL+knowledgeURL+"/capacity", new HashMap<>(), "GET");
        return JSON.parseObject(JSON.toJSONString(data), ZhiPuKnowledgeBaseCapacityVO.class);
    }

    @Override
    public ZhiPuUploadDocumentVO knowledgeUploadDocument(ZhiPuUploadDocumentDTO zhiPuUploadDocumentDTO) throws Exception {
        Map<String, ContentBody> inputData = new HashMap<>();
        inputData.put("id", new StringBody(zhiPuUploadDocumentDTO.getId(), ContentType.MULTIPART_FORM_DATA));
        inputData.put("knowledge_type", new StringBody(String.valueOf(zhiPuUploadDocumentDTO.getKnowledge_type()), ContentType.MULTIPART_FORM_DATA));
        int i = 0;
        for(MultipartFile multipartFile : zhiPuUploadDocumentDTO.getFiles()){
            inputData.put("files"+ i, new FileBody(transferToFile(multipartFile)));
            i = i + 1;
        }

        Map data = fileConnection(baselineURL+documentURL+uploadDocumentURL+"/"+zhiPuUploadDocumentDTO.getId(), inputData);
        YiLanUploadUrlVO yiLanUploadUrlVO = JSON.parseObject(JSON.toJSONString(data), YiLanUploadUrlVO.class);
        List<ZhiPuDocumentSuccessData> zhiPuDocumentSuccessDataList = yiLanUploadUrlVO.getSuccessInfos();
        for (ZhiPuDocumentSuccessData zhiPuDocumentSuccessData : zhiPuDocumentSuccessDataList){
            ContentlistEntity contentlistEntity = new ContentlistEntity();
            contentlistEntity.setId(zhiPuDocumentSuccessData.getDocumentId().toString());
            contentlistEntity.setProduct(zhiPuUploadDocumentDTO.getProduct());
            contentlistEntity.setUserId(zhiPuUploadDocumentDTO.getUserId());
            contentlistEntity.setBranch("web");
            contentlistEntity.setService("zhipu");
            contentlistEntity.setVirtualRoleUk(zhiPuUploadDocumentDTO.getVirtualRoleUk());
            contentlistMapper.insert(contentlistEntity);
        }
        return JSON.parseObject(JSON.toJSONString(data), ZhiPuUploadDocumentVO.class);
    }

    @Override
    public void knowledgeEditDocument(ZhiPuUploadDocumentDTO zhiPuEditDocumentDTO) throws Exception {
        commonConnection(baselineURL+documentURL+"/"+zhiPuEditDocumentDTO.getId(), zhiPuEditDocumentDTO, "PUT");
        QueryWrapper<ContentlistEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", zhiPuEditDocumentDTO.getId());
        ContentlistEntity contentlistEntity = contentlistMapper.selectOne(queryWrapper);
        contentlistEntity.setId(zhiPuEditDocumentDTO.getId());
        contentlistEntity.setProduct(zhiPuEditDocumentDTO.getProduct());
        contentlistEntity.setUserId(zhiPuEditDocumentDTO.getUserId());
        contentlistEntity.setBranch("web");
        contentlistEntity.setService("lingxin");
        contentlistEntity.setVirtualRoleUk(zhiPuEditDocumentDTO.getVirtualRoleUk());
    }

    @Override
    public YiLanGetKnowledgeDocumentListVO getknowledgeDocumentList(ZhiPuGetKnowledgeDocumentListDTO zhiPuGetKnowledgeDocumentListDTO) throws Exception {
        Map data = commonConnection(baselineURL+documentURL, JSON.parseObject(JSON.toJSONString(zhiPuGetKnowledgeDocumentListDTO), Map.class), "GET");
        return JSON.parseObject(JSON.toJSONString(data), YiLanGetKnowledgeDocumentListVO.class);
    }

    @Override
    public YiLanDocumentData getknowledgeDocument(String id) throws Exception {
        Map data = commonConnection(baselineURL+documentURL+"/"+id, new HashMap<>(), "GET");
        return JSON.parseObject(JSON.toJSONString(data), YiLanDocumentData.class);
    }

    @Override
    public void deleteKnowledgeDocument(String id) throws Exception {
        QueryWrapper<ContentlistEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.eq("service", "zhipu");
        ContentlistEntity contentlistEntity = contentlistMapper.selectOne(queryWrapper);
        if (contentlistEntity == null) {
            throw new Exception("操作失败：用户对改知识库数据无权限");
        }
        commonConnection(baselineURL+documentURL+"/"+id, new HashMap<>(), "DELETE");
        contentlistMapper.deleteById(contentlistEntity);
    }

    @Override
    public YiLanUploadUrlVO knowledgeUploadDocument(ZhiPuUploadUrlDTO zhiPuUploadUrlDTO) throws Exception {
        Map data = commonConnection(baselineURL+documentURL+uploadUrlURL, zhiPuUploadUrlDTO, "POST");
        YiLanUploadUrlVO yiLanUploadUrlVO = JSON.parseObject(JSON.toJSONString(data), YiLanUploadUrlVO.class);
        List<ZhiPuDocumentSuccessData> zhiPuDocumentSuccessDataList = yiLanUploadUrlVO.getSuccessInfos();
        for (ZhiPuDocumentSuccessData zhiPuDocumentSuccessData : zhiPuDocumentSuccessDataList){
            ContentlistEntity contentlistEntity = new ContentlistEntity();
            contentlistEntity.setId(zhiPuDocumentSuccessData.getDocumentId().toString());
            contentlistEntity.setProduct(zhiPuUploadUrlDTO.getProduct());
            contentlistEntity.setUserId(zhiPuUploadUrlDTO.getUserId());
            contentlistEntity.setBranch("web");
            contentlistEntity.setService("zhipu");
            contentlistEntity.setVirtualRoleUk(zhiPuUploadUrlDTO.getVirtualRoleUk());
            contentlistMapper.insert(contentlistEntity);
        }
        return yiLanUploadUrlVO;
    }

    @Override
    public void reEmbeddingknowledge(String id) throws Exception {
        connectHTTP(baselineURL+documentURL+"/"+embeddingURL+"/"+id, new HashMap<>(), "POST");
    }

//    @Override
    public String createApplication(ZhiPuApplicationData zhiPuApplicationData) throws Exception {
        String response = connectHTTP(baselineURL+applicationURL, JSON.toJSONString(zhiPuApplicationData), "POST");
        Map resultMap = JSON.parseObject(response, Map.class);
        System.out.println(resultMap);
        if (resultMap.get("data") == null) {
            throw new Exception((String) resultMap.get("message"));
        }
        return (String) resultMap.get("data");
    }

    @Override
    public ZhiPuGetApplicationListVO getApplicationList(ZhiPuGetKnowledgeBaseListDTO zhiPuGetApplicationListDTO) throws Exception {
        Map data = commonConnection(baselineURL+applicationURL, zhiPuGetApplicationListDTO, "GET");
        return JSON.parseObject(JSON.toJSONString(data), ZhiPuGetApplicationListVO.class);
    }

    @Override
    public ZhiPuApplicationData getApplication(String id) throws Exception {
        Map data = commonConnection(baselineURL+applicationURL+"/"+id, new HashMap<>(), "GET");
        return JSON.parseObject(JSON.toJSONString(data), ZhiPuApplicationData.class);
    }

    @Override
    public void editApplication(ZhiPuApplicationData zhiPuApplicationData) throws Exception {
        commonConnection(baselineURL+applicationURL+"/"+zhiPuApplicationData.getId(), zhiPuApplicationData, "PUT");
    }

    @Override
    public void deleteApplication(String id) throws Exception {
        commonConnection(baselineURL+applicationURL+"/"+id, new HashMap<>(), "DELETE");
    }

    @Override
    public ZhiPuSliceVO sliceDocument(ZhiPuSliceDTO zhiPuSliceDTO) throws Exception {
        Map data = commonConnection(baselineURL+zhiPuSliceDTO.getId()+"/slice_info", zhiPuSliceDTO, "POST");
        return JSON.parseObject(JSON.toJSONString(data), ZhiPuSliceVO.class);
    }

    @Override
    public List<YiLanDocumentData> getAllKnowledgeDocumentList(String applicationId) throws Exception {
        ZhiPuApplicationData zhiPuApplicationData = getApplication(applicationId);
        List<String> knowledgeIds = zhiPuApplicationData.getKnowledge_ids();
        ZhiPuGetKnowledgeDocumentListDTO zhiPuGetKnowledgeDocumentListDTO = new ZhiPuGetKnowledgeDocumentListDTO();
        zhiPuGetKnowledgeDocumentListDTO.setSize("1000");
        zhiPuGetKnowledgeDocumentListDTO.setPage("1");
        List<YiLanDocumentData> knowledgeDocuments = new ArrayList<>();
        for(String k : knowledgeIds) {
            zhiPuGetKnowledgeDocumentListDTO.setKnowledge_id(k);
            YiLanGetKnowledgeDocumentListVO yiLanGetKnowledgeDocumentListVO = getknowledgeDocumentList(zhiPuGetKnowledgeDocumentListDTO);
            List<YiLanDocumentData> list = yiLanGetKnowledgeDocumentListVO.getList();
            knowledgeDocuments.addAll(list);
        }
        return knowledgeDocuments;
    }

    @Override
    public String findBase() throws Exception {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("size", "500");
        Map data = commonConnection(baselineURL+knowledgeURL, hashMap, "GET");
        List dataList = (List) data.get("list");
        for(Object k : dataList){
            YiLanKnowledgeData yiLanKnowledgeData = JSON.parseObject(JSON.toJSONString(k), YiLanKnowledgeData.class);
            if(Objects.equals(yiLanKnowledgeData.getName(), "METAH默认知识库") && Objects.equals(yiLanKnowledgeData.getDescription(), "METAHCloud所有角色共用的知识库，请勿添加知识或删除")){
                log.info("智谱中默认知识库存在");
                return yiLanKnowledgeData.getId();
            }
        }
        throw new Exception("默认知识库不存在，请刷新知识库列表");
    }






}
